import fetch from 'isomorphic-fetch';
import localStorage from 'shared/utils/localStorage';
import joinUrl from 'shared/utils/joinUrl';
import * as ContentTypeEnum from './consts/ContentTypeEnum';
import toQueryString from '../utils/toQueryString';
import processHeaders from './processHeaders';

export default class Request {
  static instance = new Request;

  constructor() {
    ['get', 'post', 'put', 'patch', 'delete', 'head'].forEach((method) => {
      this[method] = (path, data, isJSON) => {
        let headers = {};
        let body;
        if (data) {
          if (data.body) {
            headers = data.headers || {};
            body = data.body;
          } else {
            body = data;
          }
        }

        const fetchConfig = {
          method,
          headers: processHeaders(method, headers),
          credentials: 'include',
        };

        let params = body;
        params={ sess_id: localStorage.get('sessId'), ...params }
        const userInfo = window.localStorage.getItem('userInfo');

        if (userInfo) {
          const userData = JSON.parse(userInfo);
          const data = {
            token: userData.token,
            uid: userData.uid,
            ssodomain: userData.ssodomain
          }
          params = { ...params, ...data, ui_random: `${new Date().getTime()}` }
        }
        if (fetchConfig.headers['Content-Type'] !== ContentTypeEnum.JSON) {
          if (!isJSON) {
            params = toQueryString(params);
          } else {
            params = JSON.stringify(params);
          }
        }

        path = joinUrl(path);
        if (method !== 'get' && method !== 'delete') {
          fetchConfig.body = params;
        } else {
          const paramsString = params ? `${params}&` : '';
          path = `${path}${path.indexOf('?') !== -1 ? '&' : '?'}${paramsString}ui_random=${new Date().getTime()}`;
        }

        return fetch(path, fetchConfig)
          .then((httpResponse = {}) => {
            const { status, statusText = '', ok } = httpResponse;

            if (ok) {
              return httpResponse.json();
            }
          })
          .then((JSONResponse) => {
            if (parseInt(JSONResponse.code, 10)  === 999) {
              window.localStorage.setItem('userInfo', '')
              __self.history.push('/Login')
              return false
            }
            return JSONResponse;
          })
          .catch((error) => {
            throw (error);
          });
      };
    });
  }
}